package com.whq.thrift.api.thrift.bs.service.thrift;

import org.apache.thrift.TProcessor;
import org.apache.thrift.server.TNonblockingServer;
import org.apache.thrift.server.TNonblockingServer.Args;
import org.apache.thrift.server.TServer;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TNonblockingServerTransport;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.whq.thrift.api.common.spring.ReloadableConfManager;
import com.whq.thrift.api.common.thriftserver.ApiRequest;
import com.whq.thrift.api.thrift.bs.service.service.BsBaseSpringService;

public class MainBsServer {
	private static final Logger LOGGER = LoggerFactory.getLogger(MainBsServer.class);

	public static void main(String[] args) throws BeansException, Exception {
		// 加载spring配置
		ClassPathXmlApplicationContext ctx = null;
		try {
			ctx = new ClassPathXmlApplicationContext("classpath:/conf/spring/applicationContext-core.xml");
		} catch (Exception e) {
			LOGGER.error("loading spring config exception: ", e);
		}

		if (ctx == null) {
			return;
		}

		ReloadableConfManager reloadableConfManager = (ReloadableConfManager) ctx.getBean("reloadableConfManager");
		int serverListenPort = reloadableConfManager.getIntPropertyValue("thrift.server.listen.port", null, 8991);

		BsBaseSpringService bsBaseSpringService = (BsBaseSpringService) ctx.getBean("bsBaseSpringService");

		int status = 0;
		try {
			// 设置服务端口为 7911
			TNonblockingServerTransport serverTransport = new TNonblockingServerSocket(serverListenPort);
			// 关联处理器与 Hello 服务的实现
			TProcessor processor = new ApiRequest.Processor(bsBaseSpringService);
			TServer server = new TNonblockingServer(new Args(serverTransport).processor(processor));
			System.out.println("start thrift server on port " + serverListenPort);
			server.serve();
		} catch (TTransportException e) {
			LOGGER.error("execute thrift server at port[" + serverListenPort + "] exception: ", e);
		}

		System.exit(status);
	}

}
